package com.example.service;

import com.example.constant.ErrorMessageConstant;
import com.example.constant.MessageTypeConstant;
import com.example.entity.Attachment;
import com.example.entity.body.impl.ASDUBody;
import com.example.entity.factory.Unpooled;
import com.example.entity.message.Message;
import com.example.util.DecodeUtil;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

/**
 * 错误报文处理
 * 
 * @author yao
 *
 */
public class ErrorHandler extends ChannelInboundHandlerAdapter {

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		// TODO Auto-generated method stub
		
		Message message = (Message) msg;

		ASDUBody body = message.getBody();
		Byte type = body.getType();
		Attachment[] attachments = body.getAttachments();
		Attachment attachment = attachments[0];

		if (type == MessageTypeConstant.ERROR_MESSAGE) {
			System.out.println("调用errorHandler");
			byte[] valueSrc = attachment.getValue();
			int value = DecodeUtil.byteToInt(valueSrc);
			switch (value) {
			case ErrorMessageConstant.NO_U:
				ctx.writeAndFlush(Unpooled.newUMessage3());
				break;
			case ErrorMessageConstant.NO_CALL_AFFIRM:
			case ErrorMessageConstant.NO_CALL_RESPOND:
			case ErrorMessageConstant.NO_CALL_END:
				ctx.writeAndFlush(Unpooled.newCallMessage());
				break;

			case ErrorMessageConstant.NO_COUNT_AFFIRM:
			case ErrorMessageConstant.NO_COUNT_RESOND:
			case ErrorMessageConstant.NO_COUNT_END:
				ctx.writeAndFlush(Unpooled.newCountMessage());
			default:
				break;
			}

		}
	}
}
